<?php

namespace app\admin\service;

use app\model\Video;
use think\facade\Session;
use app\model\User;


class IndexService
{
	private $videoModel;
	private $userModel;
	private $payRecordModel;

	public function __construct(Video $videoModel, User $userModel)
	{
		$this->videoModel = $videoModel;
		$this->userModel = $userModel;

	}

	// 获取首页数据
	public function getAdminHomePageData()
	{
		// 短剧总数
		$videoTotal = $this->videoModel->where(['is_delete' => 0])->count();
		// 会员数
		$where = [
			[
				'is_delete',
				'=',
				0
			],
			[
				'is_members',
				'=',
				1
			],
			[
				'expiration_time',
				'>',
				time()
			],
		];
		$memberTotal = $this->userModel->where($where)->count();
		$toDay = date('Ymd');
		// 今日新增用户数
		$toDayNewUserData = $this->userModel->where(['register_date' => $toDay])->field('id')->select()->toArray();
		// $toDayNewUserData1 = $this->userModel->where([['activation_time', 'like', date('Y-m-d').'%']])->field('id')->select()->toArray();
		$toDayNewUser = count($toDayNewUserData);
		$uids = array_column($toDayNewUserData, 'id');
		$startDate = date('Ym', time()) . '01';
		$endDate = date('Ymt', time());
		// 本月新增用户数
		$where = [
			[
				'register_date',
				'>=',
				$startDate
			],
			[
				'register_date',
				'<=',
				$endDate
			]
		];
		$thisMonthNewUser = $this->userModel->where($where)->count();
		// 今日用户充值数据
		$toDayUserRechargeData = $this->payRecordModel->where([
																  [
																	  'consume_date',
																	  '=',
																	  $toDay
																  ],
																  [
																	  'total_fee',
																	  '>',
																	  0
																  ]
															  ])->field('uid, status, total_fee')->select();
		$toDayUserRecharge = $toDayPaidRecharge = $toDayUnpaidRecharge = $toDayRechargeAmount = $toDayNewUserRechargeAmount = 0;
		foreach ($toDayUserRechargeData as $key => $value) {
			// 今日用户充值数
			$toDayUserRecharge = $toDayUserRecharge + 1;
			if ($value['status'] == 1) {
				// 今日已支付充值数
				$toDayPaidRecharge = $toDayPaidRecharge + 1;
				// 今日充值金额
				$toDayRechargeAmount = $toDayRechargeAmount + $value['total_fee'];
				// 今日新用户充值金额
				if (in_array($value['uid'], $uids)) {
					$toDayNewUserRechargeAmount = $toDayNewUserRechargeAmount + $value['total_fee'];
				}
			} else {
				// 今日未支付充值数
				$toDayUnpaidRecharge = $toDayUnpaidRecharge + 1;
			}
		}
		// 今日充值率
		$toDayRechargeRate = $toDayUserRecharge != 0 ? number_format($toDayPaidRecharge / $toDayUserRecharge * 100, 2) . '%' : '0%';
		$yesterDay = date('Ymd', time() - 24 * 60 * 60);
		// 昨日充值金额
		$yesterDayRechargeAmount = $this->payRecordModel->where([
																	[
																		'consume_date',
																		'=',
																		$yesterDay
																	],
																	[
																		'status',
																		'=',
																		1
																	],
																	[
																		'total_fee',
																		'>',
																		0
																	]
																])->sum('total_fee');
		$yesterDayNewUserIds = $this->userModel->where(['register_date' => $yesterDay])->column('id');
		// 昨日新用户充值
		$yesterDayNewUserRechargeAmount = $this->payRecordModel->where([
																		   'consume_date' => $yesterDay,
																		   'uid'          => $yesterDayNewUserIds,
																		   'status'       => 1
																	   ])->sum('total_fee');
		// 昨日新用户充值支付数
		$yesterDayNewUserPaidRecharge = $this->payRecordModel->where([
																		 [
																			 'status',
																			 '=',
																			 1
																		 ],
																		 [
																			 'uid',
																			 'in',
																			 $yesterDayNewUserIds
																		 ],
																		 [
																			 'total_fee',
																			 '>',
																			 0
																		 ]
																	 ])->count();
		// 昨日新用户充值未支付数
		$yesterDayNewUserUnpaidRecharge = $this->payRecordModel->where([
																		   [
																			   'status',
																			   '=',
																			   0
																		   ],
																		   [
																			   'uid',
																			   'in',
																			   $yesterDayNewUserIds
																		   ],
																		   [
																			   'total_fee',
																			   '>',
																			   0
																		   ]
																	   ])->count();
		// 昨日新用户充值率
		$yesterDayNewUserRechargeRate = $yesterDayNewUserUnpaidRecharge + $yesterDayNewUserPaidRecharge != 0 ? number_format($yesterDayNewUserPaidRecharge / ($yesterDayNewUserUnpaidRecharge + $yesterDayNewUserPaidRecharge) * 100, 2) . '%' : '0%';
		$endDate = date('Ymd', time() - 24 * 60 * 60);
		// 本月充值金额（不含当日）
		$where = [
			[
				'consume_date',
				'>=',
				$startDate
			],
			[
				'consume_date',
				'<=',
				$endDate
			],
			[
				'status',
				'=',
				1
			]
		];
		$thisMonthRechargeAmount = $this->payRecordModel->where($where)->sum('total_fee');
		// 累计充值金额（不含当日）
		$where = [
			[
				'consume_date',
				'<',
				date('Ymd')
			],
			[
				'status',
				'=',
				1
			]
		];
		$accumulatedRechargeAmount = $this->payRecordModel->where($where)->sum('total_fee');
		return [
			'video_total'                        => $videoTotal,
			'member_total'                       => $memberTotal,
			'today_new_user'                     => $toDayNewUser,
			'this_month_new_user'                => $thisMonthNewUser,
			'today_user_recharge'                => $toDayUserRecharge,
			'today_paid_recharge'                => $toDayPaidRecharge,
			'today_unpaid_recharge'              => $toDayUnpaidRecharge,
			'today_recharge_rate'                => $toDayRechargeRate,
			'today_recharge_amount'              => round($toDayRechargeAmount, 2),
			'to_day_new_user_recharge_amount'    => round($toDayNewUserRechargeAmount, 2),
			'yesterday_recharge_amount'          => $yesterDayRechargeAmount,
			'yesterday_new_user_recharge_amount' => $yesterDayNewUserRechargeAmount,
			'yesterday_new_user_paid_recharge'   => $yesterDayNewUserPaidRecharge,
			'yesterday_new_user_unpaid_recharge' => $yesterDayNewUserUnpaidRecharge,
			'yesterday_new_user_recharge_rate'   => $yesterDayNewUserRechargeRate,
			'this_month_recharge_amount'         => $thisMonthRechargeAmount,
			'accumulated_recharge_amount'        => $accumulatedRechargeAmount
		];
	}

	// 获取后台首页充值曲线图数据
	public function getAdminHomePageCurveData($params)
	{
		$where[] = [
			'status',
			'=',
			1
		];
		if (! empty($params['start_date'])) {
			$startDate = intval(str_replace('-', '', $params['start_date']));
		} else {
			$startDate = date('Ym', time()) . '01';
		}
		$where[] = [
			'consume_date',
			'>=',
			$startDate
		];
		if (! empty($params['end_date'])) {
			$endDate = intval(str_replace('-', '', $params['end_date']));
		} else {
			$endDate = date('Ymt', time());
		}
		$where[] = [
			'consume_date',
			'<=',
			$endDate
		];
		$data = $this->payRecordModel->getInfo($where, 'consume_date, total_fee');
		$totalFeeData = $result = [];
		foreach ($data as $item) {
			$totalFeeData[$item['consume_date']][] = $item['total_fee'];
		}
		$startDate = substr($startDate, 0, 4) . '-' . substr($startDate, 4, 2) . '-' . substr($startDate, 6, 2);
		$endDate = substr($endDate, 0, 4) . '-' . substr($endDate, 4, 2) . '-' . substr($endDate, 6, 2);
		$second = 86400;
		$timeDiff = (strtotime($endDate . ' +1 day') - strtotime($startDate)) / $second;
		$dateData = [];
		for ($i = 0; $i < $timeDiff; $i++) {
			$date = date('Ymd', strtotime($startDate) + $i * $second);
			$dateString = date('Y-m-d', strtotime($startDate) + $i * $second);
			$result[$dateString] = ! empty($totalFeeData[$date]) ? array_sum($totalFeeData[$date]) : 0;
		}
		return $result;
	}

	// 获取后台首页消耗曲线图数据
	public function getTotalCost()
	{
		//
	}
}